package com.lxxie.util;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

/**
 * @Description TODO
 * @Date 2021/8/27 15:13
 * @Created by xielx
 */
public class RuralDB {
    private final static String DRIVER_CLASS_NAME="oracle.jdbc.driver.OracleDriver";
    private final static String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";

    private final static String USER_NAME = "net_rural";
    private final static String PASSWORD = "net_rural";

    private final static HikariDataSource DATA_SOURCE;
    private final static NamedParameterJdbcTemplate jdbcTemplate;
    private final static DataSourceTransactionManager trans;

    static {
        DATA_SOURCE = new HikariDataSource();
        DATA_SOURCE.setJdbcUrl(URL);
        DATA_SOURCE.setDriverClassName(DRIVER_CLASS_NAME);
        DATA_SOURCE.setUsername(USER_NAME);
        DATA_SOURCE.setPassword(PASSWORD);
        DATA_SOURCE.setAutoCommit(true);
        jdbcTemplate = new NamedParameterJdbcTemplate(DATA_SOURCE);
        trans = new DataSourceTransactionManager(DATA_SOURCE);
    }

    public static NamedParameterJdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public static TransactionStatus beginTrans(){
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        return trans.getTransaction(def);
    }

    public static void commit(TransactionStatus status){
        trans.commit(status);
    }

    public static void rollback(TransactionStatus status){
        if (null != status) {
            trans.rollback(status);
        }
    }
}
